package com.wjw.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wjw.bean.AjaxResult;
import com.wjw.bean.Permission;
import com.wjw.bean.User;
import com.wjw.dao.PermissionDao;
import com.wjw.dao.UserDao;

@Controller
public class DispatcherController {
	@Autowired
	private UserDao userdao;
	@Autowired
	private PermissionDao permissiondao;
	
	@RequestMapping("login")
	public String userlogin(){
		return "login";
	}
	@RequestMapping("doLogin")
	public String dologin(String acct,String pwd,Model model){
		System.out.println("user@@@@@@@@@@@@@@@@@@@@"+acct+pwd);
		User us=userdao.find4login(acct, pwd);
		if(us==null){
			model.addAttribute("LoginFailMsg","账号密码错误");
			return "redirect:login";
		}else{
			return "main";
		}

	}
	
	@RequestMapping("doAjaxLogin")
	@ResponseBody
	public Object doajaxlogin(String loginacct,String loginpwd,HttpSession session){
		User us=userdao.find4login(loginacct, loginpwd);
		AjaxResult ar=new AjaxResult();
		if(us==null){
			ar.setSuccess(false);
		}else{
			session.setAttribute("user", us);
			
			Permission rootnode=null;
			List<Permission> permissions=permissiondao.findPerByUser(us);
			
			Set<String> uriset=new HashSet<>();
			Map<Integer, Permission> permap=new HashMap<>();
			for(Permission permission:permissions){
				permap.put(permission.getId(), permission);
				if(permission.getUrl()!=null&&!"".equals(permission.getUrl())){
					uriset.add(session.getServletContext().getContextPath()+permission.getUrl());
				}
			}
			session.setAttribute("authUriPath", uriset);
			
			for(Permission permission:permissions){
				Permission childnode=permission;
				if(childnode.getPid()==0){
					rootnode=childnode;
				}else{
					Permission parentnode=permap.get(childnode.getPid());
					parentnode.getChildren().add(childnode);
				}
			}
			
			session.setAttribute("rootPermission", rootnode);
			ar.setSuccess(true);
		}
		return ar;
	}
	
	@RequestMapping("logout")
	public String logout(HttpSession session){
		//session.removeAttribute("user");
		session.invalidate();
		return "redirect:login";
	}
	
	@RequestMapping("main")
	public String main(){
		return "main";
	}
	
	@RequestMapping("error")
	public String error(){
		return "error";
	}
}
